/**
 * package: repositories
 * author: zhaiyujin
 * description:
 */
package repositories

import (
	"fmt"
	"github.com/casbin/casbin/v2"
	"github.com/it234/goapp/pkg/convert"
	"huanteng/vendors/gcasbin"
	"huanteng/web/global/application"
	"huanteng/web/models"
)

// 设置角色权限
func SetRolePermission(enforcer *casbin.Enforcer, roleid uint) {
	var rolemenus []models.RoleMenu
	//根据角色id查询角色菜单
	err := application.DB.Where(models.RoleMenu{RoleID: roleid}).Find( &rolemenus).Error
	if err != nil {
		//return
		panic(err)
	}
	for _, rolemenu := range rolemenus {
		menu := models.Menu{}
		where := models.Menu{}
		where.ID = rolemenu.MenuID
		fmt.Println(where)
		err = application.DB.Where(where).First(&menu).Error
		if err != nil {
			//return
			panic(err)
		}

		/**
		 *菜单类型是操作
		 *casbin  r 1
		 */
		if menu.MenuType == 3 {
			enforcer.AddPermissionForUser(gcasbin.PrefixRoleID+convert.ToString(roleid), "/admin"+menu.URL, menu.Method)
		}
	}
}


// 检查用户是否有权限
func CsbinCheckPermission(userID, url, methodtype string) (bool, error) {
	return application.Enforcer.Enforce(gcasbin.PrefixUserID+userID, url, methodtype)
	//return enforcer.EnforceSafe()
}

// 为用户添加角色处理
func CsbinAddRoleForUser(userid uint)(err error){

	uid:=gcasbin.PrefixUserID+convert.ToString(userid)
	application.Enforcer.DeleteRolesForUser(uid) //用户删除角色
	var adminsroles []models.AdminRole
	application.DB.Where(models.AdminRole{AdminID: userid}).Find( &adminsroles)

	for _, adminsrole := range adminsroles {
		//添加角色为用户
		application.Enforcer.AddRoleForUser(uid, gcasbin.PrefixRoleID+convert.ToString(adminsrole.RoleID))
	}
	return
}

// 删除角色
func CsbinDeleteRole(roleids []uint) {
	if application.Enforcer == nil {
		return
	}
	for _, rid := range roleids {
		application.Enforcer.DeletePermissionsForUser(gcasbin.PrefixRoleID + convert.ToString(rid))
		application.Enforcer.DeleteRole(gcasbin.PrefixRoleID + convert.ToString(rid))
	}
}

// 设置角色权限
func CsbinSetRolePermission(roleid uint) {
	if application.Enforcer == nil {
		return
	}
	application.Enforcer.DeletePermissionsForUser(gcasbin.PrefixRoleID + convert.ToString(roleid))
	SetRolePermission(application.Enforcer, roleid)
}

